<?php

namespace App\Models;

use App\Core\Database;

abstract class BaseModel
{
    protected static string $table;
    protected static string $primaryKey = 'id';

    public static function findById(int $id): ?array
    {
        $db = Database::getInstance();
        $table = static::$table;
        $pk = static::$primaryKey;
        
        return $db->queryOne(
            "SELECT * FROM `{$table}` WHERE `{$pk}` = ?",
            [$id]
        );
    }

    public static function findAll(array $conditions = [], int $limit = 0, int $offset = 0): array
    {
        $db = Database::getInstance();
        $table = static::$table;
        
        $sql = "SELECT * FROM `{$table}`";
        $params = [];
        
        if (!empty($conditions)) {
            $whereParts = [];
            foreach ($conditions as $field => $value) {
                $whereParts[] = "`{$field}` = ?";
                $params[] = $value;
            }
            $sql .= " WHERE " . implode(' AND ', $whereParts);
        }
        
        if ($limit > 0) {
            $sql .= " LIMIT {$limit}";
            if ($offset > 0) {
                $sql .= " OFFSET {$offset}";
            }
        }
        
        return $db->query($sql, $params);
    }

    public static function count(array $conditions = []): int
    {
        $db = Database::getInstance();
        $table = static::$table;
        
        $sql = "SELECT COUNT(*) as count FROM `{$table}`";
        $params = [];
        
        if (!empty($conditions)) {
            $whereParts = [];
            foreach ($conditions as $field => $value) {
                $whereParts[] = "`{$field}` = ?";
                $params[] = $value;
            }
            $sql .= " WHERE " . implode(' AND ', $whereParts);
        }
        
        $result = $db->queryOne($sql, $params);
        return (int) $result['count'];
    }

    public static function create(array $data): int
    {
        $db = Database::getInstance();
        return $db->insert(static::$table, $data);
    }

    public static function update(int $id, array $data): bool
    {
        $db = Database::getInstance();
        $pk = static::$primaryKey;
        return $db->update(static::$table, $data, "`{$pk}` = ?", [$id]);
    }

    public static function delete(int $id): bool
    {
        $db = Database::getInstance();
        $pk = static::$primaryKey;
        return $db->delete(static::$table, "`{$pk}` = ?", [$id]);
    }

    protected static function getDb(): Database
    {
        return Database::getInstance();
    }
}

